﻿using System;
using System.IO;

namespace OposSOBuilder
{
    public class OposProjectFile
    {
        public bool ValidSolution()
        {
            if (!Directory.Exists(WorkingDirectory))
                return false;

            var file = ValidateWorkingDirectory();

            if (string.IsNullOrEmpty(file))
                return false;

            ExtractProjects(file);
            return true;
        }

        private void ExtractProjects(string file)
        {
            string line;
            System.Collections.Generic.List<string> vcxProj = new System.Collections.Generic.List<string>();
            using (StreamReader stream = new StreamReader(file))
            {
                while ((line = stream.ReadLine()) != null)
                {
                    if (line.StartsWith("Project"))
                    {
                        if (line.Contains(".vcxproj"))
                        {
                            //expected input
                            //Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestService", "TestService\TestService.vcxproj", "{B52D9A3D-6B64-4A3B-9098-576835C9B61F}"
                            vcxProj.Add(line.Split(',')[1].Trim(' ', '\"')); //get "TestService\TestService.vcxproj"
                        }
                    }
                }
            }
            Projects = vcxProj.ToArray();
        }

        private string ValidateWorkingDirectory()
        {
            var files = Directory.GetFiles(WorkingDirectory);
            var file = "";
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].EndsWith(".SLN", StringComparison.InvariantCultureIgnoreCase))
                {
                    file = files[i];
                    FileInfo fi = new FileInfo(files[i]);
                    SolutionName = fi.Name.Replace(".sln", "");
                    solutionURI = fi.FullName;
                    break;
                }
            }
            return file;
        }
        private string solutionURI;
        public string WorkingDirectory { get; set; }
        public string SolutionName { get; private set; }
        public string[] Projects { get; private set; }
    }
}
